package com.demo.framework.util;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;

public class GetClass {
    public static Set<Class<?>> getClasses(String packageName) throws IOException,ClassNotFoundException{
        Set<Class<?>> classes = new HashSet<>();
        String path = packageName.replace(".","/");
        Enumeration<URL> resources  = Thread.currentThread().getContextClassLoader().getResources(path);
        while (resources.hasMoreElements()){
            URL resource = resources.nextElement();
            String protocol =  resource.getProtocol();
            if ("file".equals(protocol) ) {
                String filePath = URLDecoder.decode(resource.getFile(),"UTF-8");
                findClassesInPackageByFile(packageName,filePath,classes);
            }
        }
        return  classes;
    }
    private static void  findClassesInPackageByFile(String packageName,String filePath,Set<Class<?>>  classes) throws ClassNotFoundException{
        File dir = new File(filePath);
        if(!dir.exists() || !dir.isDirectory()){
            return;
        }
        File [] files = dir.listFiles();
        for (File file:files) {
            if (file.isDirectory()){
                findClassesInPackageByFile(packageName+"."+file.getName(),file.getAbsolutePath(),classes);
                continue;
            }
            String className = file.getName().substring(0,file.getName().length()-6);
            Class<?> clazz = Class.forName(className);
            classes.add(clazz);
        }
    }
}


